const app = getApp()
const { authLogin, getInfo } = require('../../../api/services/login/index')
Page({
  data: {
    code: '',
    checked: false,
  },

  //选择协议
  onChange(event) {
    this.setData({ checked: event.detail })
  },

  // 选择用户协议
  getChoose() {
    if (!this.data.checked) {
      return app.toast('请勾选用户协议')
    }
  },

  // 获取手机号
  async getPhoneNumber(e) {
    let detail = e.detail
    if (e.detail.errMsg != 'getPhoneNumber:ok') {
      app.toast('手机号授权失败')
      return wx.navigateBack({ delta: 1 })
    }
    const params = {
      code: this.data.code,
      encryptedData: detail.encryptedData,
      iv: detail.iv,
      appId: 'wx5bb47834f6837927',
    }

    wx.checkSession({
      success: res => {
        this.getTokenTell(params)
      },
      fail: res => {
        this.getCode()
        this.getTokenTell(params)
      },
    })
  },

  // 获取token 手机号接口
  async getTokenTell(data) {
    console.log('params', data)

    const res = await authLogin(data)
    if (res.code != 200) {
      return app.toast(res.msg)
    }

    wx.setStorageSync('token', res.data.access_token)
    wx.switchTab({ url: '/pages/tabBar/index/index' })

    this.getUserInfo()
  },

  // 授权后获取用户信息
  async getUserInfo() {
    const res = await getInfo()
    if (res.code != 200) {
      return app.toast(res.msg)
    }
    getApp().globalData.userInfo = res.data
    wx.setStorageSync('userInfo', res.data)
    wx.setStorageSync('nickName', res.data.nickName)
  },

  // 登录获取code
  async getCode() {
    wx.login({
      success: res => {
        this.setData({ code: res.code })
      },
      fail: err => {
        console.log('登录失败！' + err)
      },
    })
  },

  bindGetUserInfo(e) {
    console.log(e.detail.userInfo)
  },

  onLoad: function (options) {
    this.getCode()
  },

  onShow: function () {
    console.log('onshow!!! login in')
    this.getCode()
  },
})
